﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Threading;
public partial class Admin_VanBan : System.Web.UI.Page
{
    private string file_save_name = "";
    private string path_save = "";
    BieumauDataContext db = new BieumauDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["login_admin"] == null)
        {
            Response.Redirect("Index.aspx");
        }
        if (!IsPostBack)
        {
            fill_data(_grid_vanban);
        }
    }
    protected void _grid_bantin_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        _grid_vanban.PageIndex = e.NewPageIndex;
        fill_data(_grid_vanban);
    }
    protected void _grid_bantin_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int idmuc = Convert.ToInt32(_grid_vanban.Rows[e.RowIndex].Cells[1].Text);
        delete_row(idmuc);
        fill_data(_grid_vanban);

    }

    public void fill_data(GridView gridview)
    {

        var i = from p in db.tblVanBans orderby p.IDVanBan descending
                select  new {IDVanBan=p.IDVanBan,TieuDe=p.TieuDe,NgayDang=p.NgayDang};
        gridview.DataSource = i;
        gridview.DataBind();
    }
    public void delete_row(int id)
    {

        var d = (from p in db.tblVanBans where p.IDVanBan == id select p).Single();
        db.tblVanBans.DeleteOnSubmit(d);
        db.SubmitChanges();


    }
  
    /// <summary>
    /// hàm upload file
    /// </summary>
    /// <param name="domain_name"></param>
    /// <param name="save_path"></param>
    /// <param name="file_upload"></param>
    public void hamupload_file(string domain_name,string save_path,FileUpload file_upload) 
    {
        
            //khai báo lấy tên tập tin
            if (file_upload.HasFile)
            {

                string[] validFileTypes = { "pdf", "PDF", "docx", "DOCX", "doc", "DOC", "xls", "pptx", "PPTX", "XLS", "XLSX", "xlsx", "ptt", "PTT" };
                string ext = System.IO.Path.GetExtension(file_upload.PostedFile.FileName);
                bool isValidFile = false;
                for (int i = 0; i < validFileTypes.Length; i++)
                {
                    if (ext == "." + validFileTypes[i])
                    {
                        isValidFile = true;
                        break;
                    }
                }
                if (!isValidFile)
                {
                    Label1.ForeColor = System.Drawing.Color.Red;
                    Label1.Text = "Sai định dạng.hãy đính kèm file có phần mở rộng như sau:" +
                    string.Join(",", validFileTypes);
                }
                else
                {
                    string new_random = MaNgauNhien_So(10);
                    string file_name = file_upload.FileName;
                    file_name = new_random + "_"+file_name;
                    file_save_name = file_name;
                    save_path += file_name;
                    path_save = save_path;
                    HttpPostedFile file = file_upload.PostedFile;
                    file_upload.SaveAs(save_path);
                }
                
               
            }
        }
        
       
      
          
    
    //Hàm sau đây sẽ tạo mã ngẫu nhiên chỉ gồm các chữ số
	public string MaNgauNhien_So(int codeCount)
	{
	    string allChar = "0,1,2,3,4,5,6,7,8,9";
	    string[] allCharArray = allChar.Split(',');
	    string randomCode = "";
	    int temp = -1;
	    Random rand = new Random();
	    for (int i = 0; i < codeCount; i++)
	    {
	        if (temp != -1)
	        {
	            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
	        }
	        int t = rand.Next(10);
	        if (temp != -1 && temp == t)
	        {
	            return MaNgauNhien_So(codeCount);
	        }
	        temp = t;
	        randomCode += allCharArray[t];
	    }
	    return randomCode;
	}

    public void xoathongtin()
    {
        txttieudevanban.Text = "";
        txttieudevanban.Focus();
        FCK_vanban.Value = "";
        
    }
    /// <summary>
    /// hàm đăng văn bản mới
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDangBT_Click(object sender, EventArgs e)
    {
        
        if (Page.IsValid)
        {
            if (FileUpload1.HasFile)
            {
                HttpPostedFile file = FileUpload1.PostedFile;
                if (file.ContentLength < 30000000)
                {

                    string save_path = Server.MapPath("~/userfiles/vanban/");
                    hamupload_file("", save_path, FileUpload1);
                    if (File.Exists(path_save))
                    {

                        DateTime dt = DateTime.Now;
                        tblVanBan vanban = new tblVanBan();
                        vanban.TieuDe = txttieudevanban.Text;
                        vanban.NoiDungTomTat = FCK_vanban.Value;
                        vanban.NgayDang = dt;
                        vanban.TomTat = txtnoidungtomtat.Text;
                        vanban.URL = "userfiles/vanban/" + file_save_name;
                        db.tblVanBans.InsertOnSubmit(vanban);
                        db.SubmitChanges();
                        fill_data(_grid_vanban);
                        xoathongtin();
                        Response.Redirect(Request.Url.AbsoluteUri);
                        Label1.ForeColor = System.Drawing.Color.Green;
                        Label1.Text = "đính kèm tập tin thành công";
                    }
                    else
                    {
                        Label1.ForeColor = System.Drawing.Color.Red;
                        Label1.Text = "không thể đính kèm tập tin,xin thử lại";
                    }
                }
                else
                {
                    Label1.ForeColor = System.Drawing.Color.Red;
                    Label1.Text = "file đính kèm quá lớn,xin chọn lại";
                }


            }
        }
    }
    protected void btn_xoa_Click1(object sender, EventArgs e)
    {
        foreach (GridViewRow row in _grid_vanban.Rows)
        {
            CheckBox checkbox = (CheckBox)row.FindControl("chkBxSelect");

            //Nếu bản ghi được chọn thì thực hiện xóa
            if (checkbox.Checked)
            {
                int idmuc = Convert.ToInt32(_grid_vanban.DataKeys[row.RowIndex].Value);
                delete_row(idmuc);
            }
        }
        fill_data(_grid_vanban);
    }

    protected void FileUpload1_Load(object sender, EventArgs e)
    {

    }
}